import Bun from "bun";
import Path from "path";
import Fs from "fs/promises";
import { Parser } from "./parser";

/**
 * 解析器
 */
export class P2cc {
    // 导出目录
    private OUTDIR: string = ""
    // 工作目录
    private DIR: string = ""

    /**
     * 构造函数
     * @param file_path 入口文件路径
     */
    constructor(file_path: string) {
        this.DIR = this.setDir(file_path)
        this.OUTDIR = Path.resolve(this.DIR, "outCpp")
        this.getFiles(this.DIR).then((files) => {
            for (const file of files) {
                const out_file = file.replace(this.DIR, this.OUTDIR).replace(".php", ".cpp")
                Parser(file, out_file)
            }
        })
    }

    /**
     * 获取所有php文件
     * @param dir 目录
     * @param results 结果
     * @returns 所有php文件
     */
    private async getFiles(dir: string): Promise<string[]> {
        // 获取目录下所有文件，且忽略outCpp目录
        const entries = await Fs.readdir(dir, { withFileTypes: true });
        const results: string[] = [];
        for (const entry of entries) {
            const fullPath = Path.join(dir, entry.name);
            if (entry.isDirectory()) {
                // 忽略名为 "outCpp" 的目录
                if (entry.name !== "outCpp") {
                    results.push(...await this.getFiles(fullPath))
                }
            } else if (entry.isFile() && Path.extname(entry.name) === ".php") {
                results.push(fullPath)
            }
        }
        return results;
    }

    /**
     * 设置工作目录
     * @param file_path 入口文件路径
     * @returns 工作目录
     */
    private setDir(file_path: string): string {
        // 获取file_path文件名称，不包括后缀
        const file = Bun.file(file_path)
        if (file.size > 0) {
            const Resolve = Path.resolve(file_path)
            return Path.dirname(Resolve)
        } else {
            throw new Error("文件不存在")
        }
    }
}